package com.book.system.servlet;

import com.alibaba.fastjson.JSON;
import com.book.system.common.R;
import com.book.system.entity.User;
import com.book.system.service.UserService;
import com.book.system.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户Servlet
 */
@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends BaseServlet {
    /**
     * 注入登陆Service
     */
    private final UserService userService = new UserServiceImpl();


    /**
     * 登陆操作
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return R 返回结果
     */
    public R<String> login(HttpServletRequest request, HttpServletResponse response) {
        // 获取请求体
        String requestBody = getRequestBody(request);
        // 解析请求体
        User user = JSON.parseObject(requestBody, User.class);
        // 调用service层登陆方法
        if (userService.login(user, request.getSession())) {
            return R.success("登陆成功");
        }
        return R.error("登陆失败，请检查用户名、密码和你的身份是否正确");
    }

    /**
     * 获取当前登陆的用户菜单
     * @param request
     * @param response
     * @return com.book.system.commom.R<java.lang.String>
     */
    public R<String> getMenu(HttpServletRequest request, HttpServletResponse response) {

        //获取session对象
        HttpSession session = request.getSession();
        //获取存放在session中的user对象
        User user = (User) session.getAttribute("user");
        if (user != null) {
            String menu = userService.getMenu(user.getFlag());
            if (menu != null && !"".equals(menu)) {
                return R.success(menu);
            }
        }
        return R.error(-1, "获取菜单失败,请尝试重新登陆");
    }

    /**
     * 退出登陆
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return com.book.system.commom.R<java.lang.String>
     */
    public R<String> logout(HttpServletRequest request, HttpServletResponse response) {

        // 获取session对象
        HttpSession session = request.getSession();
        // 销毁session对象
        session.invalidate();
        return R.success("退出成功");
    }

}
